// src/services/serialService.js

/**
 * 封装 Web Serial API 核心逻辑
 */
class SerialService {
  constructor() {
    this.port = null;        // SerialPort 对象
    this.reader = null;      // ReadableStreamDefaultReader
    this.writer = null;      // WritableStreamDefaultWriter
    this.keepReading = false;
  }

  // 1. 请求用户选择串口
  async requestPort() {
    if (!('serial' in navigator)) {
      throw new Error('浏览器不支持 Web Serial API');
    }
    // 用户交互触发
    this.port = await navigator.serial.requestPort();
    return this.port;
  }

  // 2. 打开串口
  async openPort(options = { baudRate: 9600, dataBits: 8, stopBits: 1, parity: 'none' }) {
    if (!this.port) {
      throw new Error('请先 requestPort()');
    }
    await this.port.open(options);
  }

  // 3. 开始读循环
  async startReading(onData) {
    if (!this.port || !this.port.readable) {
      throw new Error('串口未打开或不可读');
    }
    this.keepReading = true;
    const decoder = new TextDecoder();
    this.reader = this.port.readable.getReader();
    try {
      while (this.keepReading) {
        const { value, done } = await this.reader.read();
        if (done) break;
        const text = decoder.decode(value);
        onData(text);
      }
    } catch (err) {
      console.error('读取失败：', err);
    } finally {
      this.reader.releaseLock();
    }
  }

  // 4. 停止读循环
  async stopReading() {
    this.keepReading = false;
    if (this.reader) {
      await this.reader.cancel();
      this.reader.releaseLock();
      this.reader = null;
    }
  }

  // 5. 写入数据
  async writeData(dataStr) {
    if (!this.port || !this.port.writable) {
      throw new Error('串口未打开或不可写');
    }
    const encoder = new TextEncoder();
    this.writer = this.port.writable.getWriter();
    await this.writer.write(encoder.encode(dataStr));
    this.writer.releaseLock();
  }

  // 6. 关闭串口
  async closePort() {
    await this.stopReading();
    if (this.writer) {
      await this.writer.close();
      this.writer.releaseLock();
      this.writer = null;
    }
    if (this.port) {
      await this.port.close();
      this.port = null;
    }
  }
}

// 导出单例
export default new SerialService();